import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { IrInfoDetailComponent } from './ir-info-detail/ir-info-detail.component';
import { BullySubjectService } from 'app/shared/service';
import { StompClientService } from 'app/service/web-socket.service';
import { filter } from 'rxjs/operators';
import { SYSTEM_EVENT } from 'app/app.constants';
import { IncidentRecordListComponent } from './incident-record-list/incident-record-list.component';
import { IrHistoryListComponent } from './ir-history-list/ir-history-list.component';
import { ResponsePlanComponent } from './response-plan/response-plan.component';
import { IncidentService } from 'app/pages/traffic-management/incident-record/incident.service';
import { Subscription } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';
import { PublicService } from 'app/public/public.service';
@Component({
    selector: 'itmp-incident-record',
    templateUrl: './incident-record.component.html',
    styleUrls: ['./incident-record.component.css']
})
export class IncidentRecordComponent implements OnInit, OnDestroy {
    @ViewChild(IrInfoDetailComponent) private childcomponent: IrInfoDetailComponent;
    @ViewChild(IncidentRecordListComponent) private _IRListCom: IncidentRecordListComponent;
    @ViewChild(ResponsePlanComponent) private _IRResCom: IncidentRecordListComponent;
    @ViewChild(IrHistoryListComponent) private _IRHistCom: IrHistoryListComponent;
    zoneList = [];
    index = 0;
    isDetailShow = false;
    isResponsePlanActive = false;
    tempIrRecord = [];
    subscription: Subscription = null;
    responseSubscription: Subscription = null;
    isEdit = false;
    ir_id: any;
    accessButton = {
        Create: false,
        Edit: false,
        export: false,
        PRINT: false,
        GIS: false,
        MONITOR: false,
        'Add Task': false,
        Execute: false
    };
    constructor(
        private bully: BullySubjectService,
        private incidentService: IncidentService,
        private message: NzMessageService,
        private stompClientService: StompClientService,
        private pub: PublicService
    ) {}
    ngOnInit() {
        // 接受地图发来的设备创建消息
        this._createIncidentEventHandle();
        this._createResponsePlanStomp();
        this.getButtonAccess();
        this.bully.zoneListBehavior.subscribe(res => {
            this.zoneList = res['selectZoneList'] ? res['selectZoneList'] : [];
        });
    }
    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('14', this.accessButton);
    }

    ngOnDestroy(): void {
        this.bully.resetBSubject();
        if (this.subscription) {
            this.bully.resetBSubject();
            this.subscription.unsubscribe();
            this.responseSubscription.unsubscribe();
        }
    }

    tabChange(e) {
        this.isDetailShow = true;
        this.index = 2;
        setTimeout(() => {
            if (this.childcomponent) {
                this.childcomponent.initIrInfoDetail(e);
                this.childcomponent.editForm();
            }
            if (this._IRResCom && e && e.ir_ID) {
                this._IRResCom['getData'](e);
            }
        });
    }
    irSelected(e) {
        this.isDetailShow = true;
        this.tempIrRecord = e;
        setTimeout(() => {
            if (this._IRResCom) {
                this._IRResCom['getData'](e);
            }
        });
    }
    clearDetail() {
        this.childcomponent.initIrInfoDetail(this.tempIrRecord);
    }

    cancelEdit(e) {
        this.index = 0;
        this.isDetailShow = false;
    }
    clickEdit(e) {
        this.isEdit = e;
    }
    incidentPosition(e) {
        if (this._IRListCom) {
            this._IRListCom.toolbarCom.selectData = e;
            this._IRListCom.toolbarCom.positioning();
        }
    }
    irFinished() {
        this._IRHistCom.refresh();
        this._IRListCom.refresh();
    }
    irCreated(e) {
        this._IRResCom['listOfData'] = [];
        this.ir_id = e;
        this._IRListCom.refresh();
        this._IRResCom['getData']({ ir_ID: e });
        // const queryData = {
        //     condition: {
        //         ir_id: e,
        //         ip_id: null
        //     },
        //     pageNum: 1,
        //     pageSize: 10
        // };
        // const resQuery = this.incidentService.getIncidentResponsePlanList(queryData);
        // resQuery.subscribe(
        //     (resp: any) => {
        //         if (resp.messagecode === '000000' && resp.data.content.length > 0) {
        //             this.message.create('success', e + `'s response plan is creating!`);
        //             setTimeout(() => {
        //                 if (this._IRResCom) {
        //                     this._IRResCom['getData']({ ir_ID: e });
        //                 }
        //             });
        //         } else {
        //             if (!this.isResponsePlanActive) {
        //                 this.isResponsePlanActive = true;
        //                 // websocket
        //                 this.stompClientService
        //                     .createClient('jms.plan.topic.name')
        //                     .pipe(filter(response => !!response))
        //                     .subscribe(
        //                         response => {
        //                             const data = JSON.parse(response);
        //                             this.message.create('success', data + `'s response plan is created!`);
        //                             setTimeout(() => {
        //                                 if (this._IRResCom) {
        //                                     this._IRResCom['getData']({ ir_ID: e });
        //                                 }
        //                             });
        //                         },
        //                         err => {
        //                         }
        //                     );
        //             }
        //         }
        //     },
        //     (error: any) => {
        //     }
        // );
    }
    private _createResponsePlanStomp() {
        this.responseSubscription = this.stompClientService
            .createClient('jms.plan.topic.name')
            .pipe(filter(response => !!response))
            .subscribe(
                response => {
                    this.message.create('success', response + `'s response plan is created!`);
                    setTimeout(() => {
                        if (this._IRResCom) {
                            this.index = 3;
                            this._IRResCom['getData']({ ir_ID: this.ir_id });
                        }
                    }, 1000);
                },
                err => {}
            );
    }
    private _createIncidentEventHandle() {
        this.subscription = this.bully
            .getBSubject()
            .pipe(filter(res => !!res))
            .subscribe(res => {
                if (res['type'] === SYSTEM_EVENT.CREATE_EVENT) {
                    const data = res['data'];
                    this.index = 0;
                    setTimeout(() => {
                        if (this._IRListCom) {
                            this._IRListCom.changeTabPage.emit({
                                ir_ID: data['alertID'],
                                veri_State: '0', // confirmed
                                cause_IR_ID: null,
                                source: '4', // others
                                type: data.alertCode,
                                subType: null,
                                zone_ID: data['zoneID'],
                                cause: data['alertDescription'],
                                road_Name: data['roadName'], // roadName
                                location_Type: null,
                                location_SubType: null,
                                direction: data['direction'] || null,
                                start_X_Coor: data['longitude'],
                                start_Y_Coor: data['latitude'],
                                end_X_Coor: null,
                                end_Y_Coor: null,
                                q_End_Link_ID: data['linkID'], // road linkID
                                q_End_X_Coor: null,
                                q_End_Y_Coor: null,
                                QEPLatitude: null,
                                start_Time: data['detectionTime'], // incident time 的开始
                                end_Time: data['ackTime'], // incident time 的结束
                                q_Start_Time: null,
                                q_End_Time: null,
                                eTime: null,
                                remark: null,
                                lane_Blockage: null,
                                irSub: null,
                                access: null,
                                fromGis: res['fromGis']
                            });
                        }
                    }, 1000);
                }
            });
    }

    handleClick() {
        if (this._IRResCom) {
            setTimeout(() => {
                this._IRResCom['doDomToImage']();
            }, 200);
        }
    }
}
